//
//  NYDaoLanViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2020/12/30.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView
import SwiftDate

class DYDaoLanViewController: SYBaseTableViewController, UITableViewDelegate {
    
    fileprivate var vm: VGTableViewPageViewModel<Records>!
    
    var model: DYDanLanModel!
    var headView: DYHeadView!
    
    var roomModels: [DYZSRenshuChoiceModel] = []
    var canweiModels: [DYZSRenshuChoiceModel] = []
    var hasTab: Bool = false
    init(hasTab: Bool = false) {
        super.init(nibName: nil, bundle: nil)
        self.hasTab = hasTab
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = !hasTab
        self.navigationController?.navigationBar.isHidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.title = "导游导览"
        
        
        setTableView()
        setNoDataView()
        
        getData()
        getZhusuChoiceData(id: 1)
        getZhusuChoiceData(id: 3)
        getJingquChoiceData(id: 1)
        getJingquChoiceData(id: 3)
        getMeishiChoiceData(id: 2)
        getMeishiChoiceData(id: 3)
        getMeishiChoiceData(id: 4)
    }
    
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {

            self.setDataSource()
        }
    }
    
    func getData() {
        requestVM.baseRequest(disposeBag: dispose, type: .dy_firstPage, modelClass: SGBaseModel<DYDanLanModel>.self) {[weak self] (res) in
            if let `self` = self {
                self.model = res.data
                self.headView.configure(self.model)
                self.loadDataSuccessed()
            }
            
        } Error: {
            
        }
    }
    
    func getZhusuChoiceData(id: Int) {
        /* id
         1 酒店：星级 + 价格
         2 酒店分类：酒店 / 民宿
         3 酒店人数选择列表
         */
        switch id {
        case 1:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_zhusuChoiceInfo(id: "1"), modelClass: SGBaseModel<DYZSPriceAndStarChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.headView.zhusuChoice.priceChoiceView.configure(res.data ?? DYZSPriceAndStarChoiceModel())
                }
                
            } Error: {
                
            }
        case 3:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_zhusuChoiceInfo(id: "3"), modelClass: SGBaseNoPageListModel<DYZSRenshuChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.roomModels = res.data ?? []
                    self.headView.zhusuChoice.renshuChoiceView.configure(res.data ?? [])
                }
                
            } Error: {
                
            }
        default:
            break
        }
        
    }
    
    func getJingquChoiceData(id: Int) {
        /* id
         1 搜索前的 门票类型
         2 搜索后的 景点：标签
         3 搜索前的 景点价格区间，景点 + 景点 相同
         4 景区分类（地区），大屏景区讲解统计需要使用到
         */
        
        switch id {
        case 1:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquChoiceInfo(id: "1"), modelClass: SGBaseNoPageListModel<DYJQTicketChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.headView.jingquChoice.ticketChoiceView.configure(res.data ?? [])
                }
                
            } Error: {
                
            }
        case 3:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_jingquChoiceInfo(id: "3"), modelClass: SGBaseNoPageListModel<DYJQPriceChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.headView.jingquChoice.priceChoiceView.configure(res.data ?? [])
                }
                
            } Error: {
                
            }
        default:
            break
        }
    }
    
    func getMeishiChoiceData(id: Int) {
        /* id
         1 餐厅类型下拉选项
         2 餐饮搜索选择的：价格区间下拉
         3 餐饮搜索选择的：小时时间段区间
         4 餐饮搜索选择的：人数选择
         */
        switch id {
        case 2:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_meishiChoiceInfo(id: "2"), modelClass: SGBaseNoPageListModel<DYJQPriceChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.headView.meishiChoice.priceChoiceView.configure(res.data ?? [])
                }
                
            } Error: {
                
            }
        case 3:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_meishiChoiceInfo(id: "3"), modelClass: SGBaseNoPageListModel<DYMSTimeChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    var  arr = res.data ?? []
//                    arr.remove(at: 0)
                    self.headView.meishiChoice.riqiChoiceView.configure(arr)
                }
                
            } Error: {
                
            }
        case 4:
            requestVM.baseRequest(disposeBag: dispose, type: .dy_meishiChoiceInfo(id: "4"), modelClass: SGBaseNoPageListModel<DYZSRenshuChoiceModel>.self) {[weak self] (res) in
                if let `self` = self {
                    self.headView.meishiChoice.renshuChoiceView.configureMeishi(res.data ?? [])
                }
                
            } Error: {
                
            }
        default:
            break
        }
    }
    
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView!.register(DYMeishiCell.self, forCellReuseIdentifier: "DYMeishiCell")
        self.tableView!.register(DYDaoLanCell.self, forCellReuseIdentifier: "DYDaoLanCell")
        self.view.addSubview(self.tableView!)
        
        self.headView = DYHeadView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 412.autoWidth()), currentVC: self)
        self.headView.clickedClosure = {[weak self] (index) in
            if let `self` = self {
                
//                switch index {
//                case 0:
//                    self.setZhusuChoiceModel()
//
//                case 1:
//                    self.setJingquChoiceModel()
//
//                case 2:
//                    self.setMeishiChoiceModel()
//
//                default:
//                    break
//                }
            }
        }
        
        self.tableView.tableHeaderView = self.headView
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                    if indexPath.section == 1 {
                        let m: DYScenicSpotVOListModel = (self.model.scenicSpotVOList?[indexPath.row])!
                        let vc = DYJingquDetailViewController(m.id ?? "0")
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            DYScenicSpotVOListSection(header: "", items: [DYScenicSpotVOListModel()]),
            DYScenicSpotVOListSection(header: "", items: self.model.scenicSpotVOList ?? [])
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<DYScenicSpotVOListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                if ip.section == 1 {
                    
                    let cell: DYDaoLanCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                        as? DYDaoLanCell ?? DYDaoLanCell(style: .default, reuseIdentifier: "Cell")
                    cell.configureView(item)
                    cell.selectionStyle = .none
                    return cell
                } else {
                    
                    let cell: DYMeishiCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                        as? DYMeishiCell ?? DYMeishiCell(style: .default, reuseIdentifier: "Cell")
                    cell.currentVC = self
                    cell.selectionStyle = .none
                    cell.configureView(self.model.restaurants ?? [])
                    return cell
                }
                
        },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
                
                
        })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func rightAction() {
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let titleHeader = DYTitleHeader(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 56.autoWidth()))
        if section == 0 {
            titleHeader.nameLb.text = "餐饮美食"
            titleHeader.chakan.setTitle("全部  >", for: .normal)
        } else {
            titleHeader.nameLb.text = "旅游景区"
            titleHeader.chakan.setTitle("更多  >", for: .normal)
        }
        titleHeader.currentVC = self
        titleHeader.clickedClosure = {[weak self] _ in
            if let `self` = self {
                
                if section == 0 {
                    let vc = DYMSListViewController(params: [:])
                    self.navigationController?.pushViewController(vc, animated: true)
                } else {
                    let vc = DYListViewController(params: [:])
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            }
        }
        return titleHeader
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 56.autoWidth()
    }
    
}





//自定义Section
struct DYScenicSpotVOListSection {
    var header: String
    var items: [Item]
}

extension DYScenicSpotVOListSection : AnimatableSectionModelType {
    typealias Item = DYScenicSpotVOListModel

    var identity: String {
        return header
    }

    init(original: DYScenicSpotVOListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension DYScenicSpotVOListModel: IdentifiableType {
    var identity: String {
        return id!
    }

    typealias Identity = String
}
